<?php

$qbi_order_line_count=0;

?>
<html>
<head>
<style type="text/css"><!--

#progress_bar {
 margin: 1px;
 height: 20px;
 padding: 1px;
 border: 1px solid #000;
 width: 475px;
 background: #fff;
 color: #000;
 float: left;
 clear: right;
 top: 38px;
 z-index: 9
}

.percents {
 background: #FFF;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 position:absolute;
 width:475px;
 z-index:10;
 left: 10px;
 top: 38px;
 text-align: center;
}

.blocks {
 background: #EEE;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 width: 10px;
 position: absolute;
 z-index:11;
 left: 12px;
 top: 38px;
 filter: alpha(opacity=50);
 -moz-opacity: 0.5;
 opacity: 0.5;
 -khtml-opacity: .5
}

-->
</style>
<link rel="stylesheet" type="text/css" media="all" href="js/skins/aqua/theme.css" title="win2k-cold-1" />
 <script type="text/javascript" src="js/calendar.js"></script>
  <script type="text/javascript" src="js/lang/calendar-en.js"></script>
  <script type="text/javascript" src="js/calendar-setup.js"></script>
</head>
<body>


<?
if (ob_get_level() == 0) {
   ob_start();
}

if (file_exists('includes/local/configure.php')) include('includes/local/configure.php');

  require('includes/configure.php');

// include the list of project database tables
  require(DIR_WS_INCLUDES . 'database_tables.php');

// include the database functions
  include_once(DIR_WS_FUNCTIONS . 'database.php');

// make a connection to the database... now
  tep_db_connect() or die('Unable to connect to database server!');

// set application wide parameters
  $configuration_query = tep_db_query('select configuration_key as cfgKey, configuration_value as cfgValue from ' . TABLE_CONFIGURATION);
  while ($configuration = tep_db_fetch_array($configuration_query)) {
    define($configuration['cfgKey'], $configuration['cfgValue']);
  }

// define our general functions used application-wide
  require(DIR_WS_FUNCTIONS . 'general.php');

$language = english;


// define our localization functions
  require(DIR_WS_FUNCTIONS . 'localization.php');

// entry/item info classes
  require(DIR_WS_CLASSES . 'object_info.php');


// check if a default currency is set
  if (!defined('DEFAULT_CURRENCY')) {
    $messageStack->add(ERROR_NO_DEFAULT_CURRENCY_DEFINED, 'error');
  }

require(DIR_WS_LANGUAGES . $language . '/qbi_general.php');
require(DIR_WS_LANGUAGES . $language . '/orders.php'); // needed for email text
require(DIR_WS_INCLUDES . 'qbi_version.php');
require(DIR_WS_INCLUDES . 'qbi_definitions.php');
require(DIR_WS_FUNCTIONS . 'qbi_functions.php');
require(DIR_WS_CLASSES . 'qbi_classes.php');

$tdate_qbi = date("Y-m-d__H_i");

if(!isset($run_process)){
?>
<form method="post" action="">
  <table border="0" align=center cellspacing="0" cellpadding="3">
    <tr>
      <td colspan="2" align=center>Select File Detail Options</td></tr>
    <tr>
      <td width="80" align=left><input name="type" type="radio" value="date_selection" /> Date</td>
      <td width="250" align=left>From: <input name="from_date" type="text" id="from_date" size="10" maxlength="10" />
      To: <input name="to_date" type="text" id="to_date" size="10" maxlength="10" />
      </td>
      <script type="text/javascript">
          Calendar.setup({
              inputField     :    "from_date",     // id of the input field
              ifFormat       :    "%Y-%m-%d",      // format of the input field
              button         :    "from_date",  // trigger for the calendar (button ID)
              align          :    "Bl",           // alignment (defaults to "Bl")
              singleClick    :    true
          });
</script>
<script type="text/javascript">
    Calendar.setup({
        inputField     :    "to_date",     // id of the input field
        ifFormat       :    "%Y-%m-%d",      // format of the input field
        button         :    "to_date",  // trigger for the calendar (button ID)
        align          :    "Bl",           // alignment (defaults to "Bl")
        singleClick    :    true
    });
</script>
    </tr>

    <tr>
      <td align=left><input name="type" type="radio" value="order_selection" />
      Product#</td>
      <td align=left><input name="products_number" type="text" size="10" maxlength="10" />
      </td>
    </tr>
    <tr>
      <td align=left><input name="type" type="radio" value="all_selection" />
      All</td>
      <td align=left>Download all products</td>
    </tr>
    <?php
  $sqlqq="SELECT * FROM ".TABLE_PRODUCTS." where qbi_imported='0'";
  $resultqq=tep_db_query($sqlqq);
  $total_filesqq = mysql_num_rows($resultqq);

    ?>

  <!--      <tr>
          <td align=left><input name="type" type="radio" value="new_selection" checked />
          New Orders</td>
          <td align=left>Download <? echo $total_filesqq ?> new products</td>
    </tr>
    -->
      <?php
      $sqlqq2="SELECT * FROM ".TABLE_PRODUCTS." where qbi_imported='1'";
      $resultqq2=tep_db_query($sqlqq2);
      $total_filesqq2 = mysql_num_rows($resultqq2);

        ?>

   <!--         <tr>
              <td align=left><input name="type" type="radio" value="previous_selection" />
              Previous Orders</td>
              <td align=left>Download <? echo $total_filesqq2 ?> from the previous product items build.</td>
        </tr>
-->

    <tr>
      <td align=left></td>
      <td align=left>
        <input type="submit" name="Submit" value="Submit" />
      </td>
    </tr>
  </table>

<input type=hidden name=run_process value=run_process>
</form>
<?
exit;}



$stage="process";
$engine="products";

if($type == "date_selection"){$whereclause=" AND p.products_date_added >= '$from_date' and p.products_date_added <= '$to_date'";$qbiimported=2;}
elseif($type == "order_selection"){$whereclause=" AND p.products_id = '$products_number'";$qbiimported=2;}
//elseif($type == "new_selection"){$whereclause=" AND qbi_imported='0'";$qbimported=0;}
//elseif($type == "previous_selection"){$whereclause=" WHERE qbi_imported='1'";$qbimported=2;}
else{$whereclause="";}

if (isset($stage) AND $stage=='process' AND isset($engine) AND $engine=='products') {

// Update prior products
  if ($qbimported==0) $result2=tep_db_query("UPDATE ".TABLE_PRODUCTS." SET qbi_imported=2 WHERE qbi_imported=1");

// Read product data
  //(ITEM_ACTIVE==1) ? $whereclause="AND products_status='1' " : $whereclause="";
 $resultpd = tep_db_query("SELECT * FROM ".TABLE_PRODUCTS." AS p, ".TABLE_PRODUCTS_DESCRIPTION." AS pd WHERE p.products_id=pd.products_id ".$whereclause." ORDER BY p.products_model");
$total_files = mysql_num_rows($resultpd);
// Check for products
  if ($myrowpd=tep_db_fetch_array($resultpd)) {

// Open output file
    $handle=fopen("qbi_output/qbi_products_".$tdate_qbi.".iif", "wb");

// Create iif header
    $prod_data="!INVITEM\tNAME\tINVITEMTYPE\tDESC\tPURCHASEDESC\tACCNT\tASSETACCNT\tCOGSACCNT\tPRICE\tCOST\tTAXABLE\tPAYMETH\tTAXVEND\tTAXDIST\tPREFVEND\tREORDERPOINT\tQNTY\tEXTRA\n";

// Set item type
    if (ITEM_IMPORT_TYPE==2) {
	  $item_type="SERV";
    } elseif (ITEM_IMPORT_TYPE==1) {
	  $item_type="PART";
    } else {
	  $item_type="INVENTORY";
    }

// Loop through each product
	do {
      $prod_id=$myrowpd["products_id"];
	  $prod_price=round($myrowpd["products_price"],2);
	  $myrowpd["products_tax_class_id"]>0 ? $ptaxable="Y" : $ptaxable="N";
      $prod_prefix="";
	  $prod_name=$myrowpd["products_model"];
      $prod_desc=$myrowpd["products_name"];
      $prod_quan=$myrowpd["products_quantity"];

// Add product line without attributes
    //$prod_data.="INVITEM\t$prod_name\t$item_type\t$prod_desc\t$prod_desc\t".ITEM_ACCT."\t".ITEM_ASSET_ACCT."\t".ITEM_COG_ACCT."\t$prod_price\t0\t$ptaxable\t\t\t\t\t\t$prod_quan\t\n";

// Add product line if 1 or 2 attributes
      $resultpx = tep_db_query("SELECT DISTINCT options_id FROM ".TABLE_PRODUCTS_ATTRIBUTES." WHERE products_id='$prod_id' ORDER BY options_id");
     $grows=mysql_num_rows($resultpx);

     if($grows ==0){
	 $prod_data.="INVITEM\t$prod_name\t$item_type\t$prod_desc\t$prod_desc\t".ITEM_ACCT."\t".ITEM_ASSET_ACCT."\t".ITEM_COG_ACCT."\t$prod_price\t0\t$ptaxable\t\t\t\t\t\t$prod_quan\t\n";}

	 if ($myrowpx=tep_db_fetch_array($resultpx)) {
	    $options_id=$myrowpx["options_id"];
		$option_data=prod_options($prod_id,$options_id,$prod_name,$prod_desc,$prod_price);

		if ($myrowpx=tep_db_fetch_array($resultpx)) {
          $options_id_sub=$myrowpx["options_id"];

		  foreach ($option_data as $option_row) {
		    $option_data=prod_options($prod_id,$options_id_sub,$option_row[0],$option_row[1],$option_row[2]);

		    foreach ($option_data as $option_row) {
		      //$prod_data.="INVITEM\t".$option_row[0]."\t$item_type\t".$option_row[1]."\t".$option_row[1]."\t".ITEM_ACCT."\t".ITEM_ASSET_ACCT."\t".ITEM_COG_ACCT."\t".$option_row[2]."\t0\t$ptaxable\t\t\t\t\t\t\t\n";

			$prod_data.="INVITEM\t".$option_row[0]."\t$item_type\t".$option_row[1]."\t".$option_row[1]."\t".ITEM_ACCT."\t".ITEM_ASSET_ACCT."\t".ITEM_COG_ACCT."\t".$option_row[2]."\t0\t$ptaxable\t\t\t\t\t\t\t\n";
			}
		  }
		}
		else {
		  foreach ($option_data as $option_row) {

				$prod_data.="INVITEM\t".$option_row[0]."\t$item_type\t".$option_row[1]."\t".$option_row[1]."\t".ITEM_ACCT."\t".ITEM_ASSET_ACCT."\t".ITEM_COG_ACCT."\t".$option_row[2]."\t0\t$ptaxable\t\t\t\t\t\t\t\n";

		  }
		}
      }

// Update qbi_imported status of order
      if ($qbimported==0) $result1=tep_db_query("UPDATE ".TABLE_PRODUCTS." SET qbi_imported=1 WHERE products_id=$prod_id");


$qbi_order_line_count++;
$i=($qbi_order_line_count/$total_files)*100;
$i=number_format($i, 2, '.', '');
   $d = $d + 1;
   $m=$d+10;
   echo '<div class="percents" id=progress_bar>' . $i . '%&nbsp;complete on order line '.$qbi_order_line_count.' of '.$total_files.' orders.</div>';
   flush();
   ob_flush();


	} while ($myrowpd = tep_db_fetch_array($resultpd));

// Write product data
    fwrite($handle,$prod_data);


	ob_end_flush();
   $filename="qbi_output/qbi_products_".$tdate_qbi.".iif";

?>
<div class="percents" style="z-index:12">Done: <a href="<?php echo $filename ?>">Click to Download File</a></div>


</body>
</html>
<?php


// Close file
    fclose($handle);

// Download file
 //   if (QBI_DL_IIF==1) {
   //   $filename="qbi_output/qbi_prod.iif";
//      $size=filesize($filename);
 //     header("Pragma: public");
 //     header("Cache-Control: private");
    // header("Content-type: application/octet-stream");
    //  header("Content-Disposition: attachment; filename=qbi_prod.iif");
 //     header("Content-length: $size");
 //     readfile("$filename");
  //    exit();
   // }
  }
}
?>
